# -*- coding: utf-8 -*-
'''
#----------------------------------------------------------------------------------------
# 功能：编译xcode项目并打ipa包
# 使用说明：
#		编译project
#			build_ipa -p <project directory> [-c <project configuration>] [-o <ipa output directory>] [-t <target name>] [-n]
#		编译workspace
#			build_ipa -p <workspace directory> -w -s <schemeName> [-c <project configuration>] [-n]
#
# 参数说明：
#			-p|--project					 	PATH				工程路径
#			-c|--configuration			 		NAME				工程的configuration,默认为Release。
#			-o|--output					 		PATH				生成的ipa文件,默认为工程根路径下的”build/ipa-build“文件夹中
#			-t|--target					 		NAME				需要编译的target的名称
#			-w|--workspace											编译workspace	
#			-s|--scheme 					 	NAME				对应workspace下需要编译的scheme
#			-n|--clean												编译前是否先clean工程
#----------------------------------------------------------------------------------------
'''
import os
import glob
import argparse
import time
import shutil
from flib.utils import *

def usage():
    ZLPrint(__doc__)

def plistbuddy(*args, **kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute("/usr/libexec/PlistBuddy " + param.format(**kwargs), logout=False)

def xcode_cmd(*args,**kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute("xcodebuild " + param.format(**kwargs))

def xcrun(*args,**kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute("xcrun " + param.format(**kwargs))

def compile_pro(args):
    #清理工程
    if not args.clean: xcode_cmd("clean -project {proj} -configuration {conf}", proj=args.project, conf=args.configuration or "Release")
    (dirpath, appname) = os.path.split(args.project)
    build_path = os.path.join(dirpath, "build")
    appdirname="Release-iphoneos"
    if args.configuration == "Debug": appdirname="Debug-iphoneos"
    elif args.configuration == "Distribute": appdirname="Distribute-iphoneos"
    if not args.workspace:
        xcode_cmd("-project {proj} -configuration {conf} -scheme {scheme} archive -archivePath {archpath}",
        	proj=args.project, conf=args.configuration or "Release",scheme=args.scheme,
        	archpath=os.path.join(build_path, "archive"))
    else:
        # 编译后文件路径(仅当编译workspace时才会用到)
        compiled_path = os.path.join(build_path,appdirname)
        wk = glob.glob(os.path.join(args.project,"*.xcworkspace"))[0]
        xcode_cmd("-workspace {wk} -scheme {scheme} -configuration {conf} CONFIGURATION_BUILD_DIR='{compiled_path}' ONLY_ACTIVE_ARCH=NO",
                  wk=wk,scheme=args.scheme,conf=args.configuration,compiled_path=compiled_path)
    app_path = glob.glob(os.path.join(build_path, appdirname, "*.app"))[0]
    (dirpath, appname) = os.path.split(app_path)
    # app文件中Info.plist文件路径
    app_infoplist_path = os.path.join(build_path,appdirname,appname,"Info.plist")
    # 取版本号
    result = plistbuddy("-c",'''"print CFBundleShortVersionString"''',app_infoplist_path)
    bundleShortVersion = result[0]
    # 取build值
    result = plistbuddy("-c", '''"print CFBundleVersion"''', app_infoplist_path)
    bundleVersion = result[0]
    # 取displayName
    result = plistbuddy("-c", '''"print CFBundleDisplayName"''', app_infoplist_path)
    displayName = result[0]
    # IPA名称
    ipa_name = displayName + "_" + bundleShortVersion + "_" + args.configuration + "_" + bundleVersion + "_" + time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
    ZLPrint("IPA Name:",ipa_name)
    #打包ipa
    if os.path.exists(os.path.join(build_path,"ipa-build")): os.makedirs(os.path.join(build_path,"ipa-build"))
    ipa_path = os.path.join(build_path,"ipa-build",ipa_name)+".ipa"
    #xcrun("-sdk {sdk} PackageApplication -v {app} -o {ipa}",sdk="iphoneos",app=os.path.join(build_path, appdirname, "*.app"),ipa=ipa_path)
    xcode_cmd("-sdk {sdk} -exportArchive -exportFormat ipa -archivePath {archpath} -exportPath {ipa}", 
    	sdk="iphoneos",
    	archpath=os.path.join(build_path, "archive.xcarchive"),
    	ipa=ipa_path)
    if os.path.exists(args.output):shutil.copyfile(ipa_path,args.output)

def main():
    parser = argparse.ArgumentParser(prog='build_ipa', usage=__doc__)
    parser.add_argument("--project","-p", help="工程路径", type=str, default="/Volumes/SHARED/WorkSpace/Unity/LuaGame-iOS-XCode/Unity-iPhone.xcodeproj")
    parser.add_argument("--configuration","-c", help="工程的configuration,默认为Release", type=str, default="Release")
    parser.add_argument("--output","-o", help="生成的ipa文件,默认为工程根路径下的”build/ipa-build“文件夹中", type=str, default="")
    parser.add_argument("--target","-t", help="需要编译的target的名称", type=str, default="Unity-iPhone")
    parser.add_argument("--workspace","-w", help="编译workspace", action="store_true")
    parser.add_argument("--scheme","-s", help="对应workspace下需要编译的scheme", type=str, default="Unity-iPhone")
    parser.add_argument("--clean","-n", help="编译前是否先clean工程", action="store_true")

    args = parser.parse_args()
    if not args.project: usage(),exit(0)
    if args.workspace and not args.scheme: usage(),exit(0)
    if not os.path.exists(args.project): usage(),exit(0)

    compile_pro(args)

if __name__ == '__main__':
    main()